package com.huaguoguo.spring.context;

import com.huaguoguo.spring.annotation.Component;
import com.huaguoguo.spring.annotation.Configuration;
import com.huaguoguo.spring.annotation.Service;
import com.huaguoguo.spring.context.config.BeanDefinition;
import com.huaguoguo.spring.execption.BeanRegisterExecption;
import com.huaguoguo.spring.util.ClassUtils;
import com.huaguoguo.spring.util.StringUtils;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * description: 注册要扫描的bena的声明
 * author:huaguoguo
 * Date:2018/12/6
 * Time:23:05
 */
public class RegisterBeanDefinition {

    public Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>(256);

    void register(String basePackage){
        Set<Class<?>> classSet = ClassUtils.getClassSet(basePackage);
        for (Class<?> aClass : classSet) {
            beanDefinition(aClass);
        }
    }



    private void beanDefinition(Class<?> aClass){
        Annotation[] annotations = aClass.getAnnotations();
        if (annotations != null) {
            for (Annotation annotation : annotations) {
                String annotationName = annotation.annotationType().getSimpleName();
                String beanName = null;
                switch (annotationName) {
                    case "Configuration":
                        beanName = ((Configuration) annotation).value();
                        new ConfigurationBeanLoad().beanload(this,aClass);
                        break;
                    case "Service":
                        beanName = ((Service) annotation).value();
                        break;
                    case "Component":
                        beanName = ((Component) annotation).value();
                        break;
                    default:
                        continue;
                }
                if (StringUtils.isEmpty(beanName)) {
                    beanName = StringUtils.toLowerCaseFirstOne(aClass.getSimpleName());
                }
                if (beanDefinitionMap.containsKey(beanName)) {
                    throw new BeanRegisterExecption(String.format("存在同名bean：%s,请检查你的代码！",beanName));
                }
                BeanDefinition beanDefinition = new BeanDefinition();
                beanDefinition.setBeanName(beanName);
                beanDefinition.setBeanType(aClass);
                beanDefinitionMap.put(beanName,beanDefinition);
                return;
            }

        }
    }
}
